import json
import tornado.web
import logging
import datetime
import hashlib
from tornado.web import HTTPError
logger = logging.getLogger('boilerplate.' + __name__)



class BaseHandler(tornado.web.RequestHandler):
    access = True
    """A class to collect common handler methods - all other handlers should
    subclass this one.
    """
    def __init__(self, *args, **kwargs):
        tornado.web.RequestHandler.__init__(self, *args, **kwargs)
        self.db = self.settings['db']
        self.content = {}
        # self._check_access()
        if not self.access:
             raise HTTPError(404)


    def prepare(self):
        self._check_access()
        # if not self.access:
        #     self.response_msg(400,'request httpheaders error')

    def load_json(self):
        """Load JSON from the request body and store them in
        self.request.arguments, like Tornado does by default for POSTed form
        parameters.

        If JSON cannot be decoded, raises an HTTPError with status 400.
        """
        try:
            self.request.arguments = json.loads(self.request.body)
        except ValueError:
            msg = "Could not decode JSON: %s" % self.request.body
            logger.debug(msg)
            raise tornado.web.HTTPError(400, msg)

    def get_json_argument(self, name, default=None):
        """Find and return the argument with key 'name' from JSON request data.
        Similar to Tornado's get_argument() method.
        """
        if default is None:
            default = self._ARG_DEFAULT
        if not self.request.arguments:
            self.load_json()
        if name not in self.request.arguments:
            if default is self._ARG_DEFAULT:
                msg = "Missing argument '%s'" % name
                logger.debug(msg)
                raise tornado.web.HTTPError(400, msg)
            logger.debug("Returning default argument %s, as we couldn't find "
                    "'%s' in %s" % (default, name, self.request.arguments))
            return default
        arg = self.request.arguments[name]
        logger.debug("Found '%s': %s in JSON arguments" % (name, arg))
        return arg

    def _check_access(self):
        """ 请求头验证 """
        if 'X-Access-Code' in self.request.headers:
            if self.request.headers['X-Access-Code'] != 'code.healthMange.lovepinyao.com':
                self.access = False
            else:
                pass
        else:
            self.access = False
        if 'X-Access-Key' in self.request.headers:
            if self.request.headers['X-Access-Key'] != 'key.healthMange.lovepinyao.com':
                self.access = False
            else:
                pass
        else:
            self.access = False
        if 'Content-Type' in self.request.headers:
            if self.request.headers['Content-Type'] != 'application/json;charset=utf-8':
                self.access = False
            else:
                pass
        else:
            self.access = False
        #获取所有的请求参数
        arguments = self.request.arguments
        arguments_list = []
        md5_str = ''
        #遍历所有参数,获取参数的KEY
        for key in arguments:
            arguments_list.append(key)
        arguments_list.sort()
        for item in arguments_list:
            md5_str = md5_str + arguments[item][0].decode('utf-8')
        m = hashlib.md5()
        m.update(md5_str.encode())
        request_sign = m.hexdigest()

        if 'X-Request-Sign' in self.request.headers:
            if request_sign != self.request.headers['X-Request-Sign']:
                self.access = False
            else:
                pass
        else:
            self.access = False


    def formart(self, cousor):
        info = []
        if isinstance(cousor, datetime.date):
            return str(cousor)
        if isinstance(cousor, dict):
            if '_id' in cousor:
                cousor['objectId'] = str(cousor['_id'])
                del cousor['_id']
            if 'created_at' in cousor:
                cousor['created_at'] = str(cousor['created_at'].strftime("%Y-%m-%d %H:%M"))
            if 'brith' in cousor:
                cousor['brith'] = str(cousor['birth'].strftime("%Y-%m-%d"))
            return cousor
        else:
            for e in cousor:
                if '_id' in e:
                    e['ObjectId'] = str(e['_id'])
                    del e['_id']
                if 'create_at' in e:
                    e['created_at'] = str(e['created_at'].strftime("%Y-%m-%d %H:%M"))
                info.append(e)
        return info

    def return_message(self, ret):
        if ret:
            self.response_msg(200, 'add success')
        else:
            self.response_msg(400, 'add fail')


    @tornado.gen.coroutine
    def response_msg(self, code=200, msg=None, data=[], count=False):
        """ 返回统一接口 """
        self.set_status(200)
        self.set_header("Content-Type", "application/json")
        self.set_header("Server", "lovepinyao.com-Server-Group")
        self.set_default_headers()
        # 组装返回信息
        response_info = {}
        if code:
            response_info['code'] = code
        if msg:
            response_info['message'] = msg
        response_info['results'] = data
        if count:
            response_info['count'] = count
        self.write(json.dumps(response_info))
        self.finish()

    @tornado.gen.coroutine
    def get_select_argument(self, names, unnecessary=[]):
        """ 封装获取参数方法,参数存在必须和非必须2种,必须字段获取出错，
        直接清空返回,报错.非必须字段获取出错则直接跳过
        """
        arguments = {}
        error = ''
        if isinstance(names, list):
            if len(names):
                for name in names:
                    try:
                        arguments[name] = self.get_argument(name)
                    except Exception as e:
                        if not error:
                            error = str(e)
        # 获取非必须字段
        if len(unnecessary):
            for un in unnecessary:
                try:
                    arguments[un] = self.get_argument(un)
                except Exception as e:
                    # 若在非必须字段中获取错误的话不做处理
                    pass
        # 只要有错误发生，则直接清空返回
        if error:
            arguments = {}
        return (arguments, error)
    def format_datetime(self, date):
        """
        给一个datetime格式的数据，返回‘今天’，‘昨天’
        :param date:
        :return:
        """
        today = datetime.date.today()
        yesterday = datetime.date.today() - datetime.timedelta(1)
        if date.date() == today:
            return '今天'
        elif date.date() == yesterday:
            return '昨天'
        else:
            return str(date.strftime("%Y-%m-%d"))

    def datetime2week(self, date):
        obj_date = date.date()
        ret = obj_date.weekday()
        if ret == 1:
            return '周二'
        elif ret == 2:
            return '周三'
        elif ret == 3:
            return '周四'
        elif ret == 4:
            return '周五'
        elif ret == 5:
            return '周六'
        elif ret == 6:
            return '周日'
        elif ret == 0:
            return '周一'